package dao;

import db.DB;
import entity.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * Created by gwei on 2017/5/26.
 */
public class UserDao {
    /**
     * 通过主键id获取
     * @param id
     * @return
     */
    public User get(int id){
        User result = null;
        String sql = "select * from user where id = ?";
        DB db = new DB(sql);
        db.setInt(1,id);
        ResultSet rs = db.select();
        try {
            if (rs.next()){
                result = new User();
                result.setId(rs.getInt("id"));
                result.setUsername(rs.getString("username"));
                result.setCreate_time(rs.getLong("create_time"));
            }
        } catch (SQLException ex) {
            System.out.println("Error: " + ex.getMessage());
        }finally {
            db.close();
        }
        return result;
    }

    /**
     * 通过用户名和密码获取用户
     * @param username
     * @param password
     * @return
     */
    public User get(String username, String password){
        User result = null;
        String sql = "select * from user where username = ? and password = ? limit 1";
        DB db = new DB(sql);
        db.setString(1,username);
        db.setString(2,password);
        ResultSet rs = db.select();
        try {
            if (rs.next()){
                result = new User();
                result.setId(rs.getInt("id"));
                result.setUsername(rs.getString("username"));
                result.setCreate_time(rs.getLong("create_time"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  result;
    }

    /**
     * 通过用户名判断用户是否存在
     * @param username

     * @return
     */
    public int get(String username){
        int result = 0;
        String sql = "select * from user where username = ? limit 1";
        DB db = new DB(sql);
        db.setString(1,username);
        ResultSet rs = db.select();
        try {
            if (rs.next()){
                result = 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  result;
    }

    /**
     * 新增一个用户
     * @param username
     * @param password
     * @return
     */
    public int add(String username,String password){
        int result = 0;
        if (this.get(username) == 1){
            return result;
        }
        String sql = "insert into user(username,password,create_time) values(?,?,?)";
        DB db = new DB(sql);
        db.setString(1, username);
        db.setString(2,password);
        db.setLong(3,new Date().getTime());
        result = db.update();
        db.close();
        return result;
    }
}
